package game_engine.core;

import java.awt.Color;
import java.util.EmptyStackException;
import java.util.Stack;


public class GECore implements Runnable {
	
	public long tick = 0;
	public long lastTick = 0;
	
	private GameStage currentStage;
	
	private Thread coreThread;
	
	private Stack<Object[]> textureToLoad;
	private boolean textureLoaded = true;
	
	private Stack<Object[]> fontToLoad;
	private boolean fontLoaded = false;
	
	private boolean running = false;
	
	public GECore() {
		textureToLoad = new Stack<Object[]>();
		fontToLoad = new Stack<Object[]>();
		coreThread = new Thread(this, "CoreThread");
	}

	private void update() {
		updateTick();
		if(currentStage!=null)currentStage.update(tick);
		if(tick<30)
			try {
				Thread.sleep(30-tick);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
	}
	
	public Object[] getTextureToLoad() {
		try {
			return textureToLoad.pop();
		} catch (EmptyStackException e) {
			return null;
		}
	}
	
	public void addTextureToLoad(String image, Color transColor) {
		textureLoaded = false;
		Object[] o = new Object[] {image, transColor};
		textureToLoad.push(o);
	}
	
	public boolean isAllTextureLoaded() {
		return textureLoaded;
	}
	
	public void setTextureLoaded(boolean textureLoaded) {
		this.textureLoaded = textureLoaded;
	}
	
	public Object[] getFontToLoad() {
		try {
			return fontToLoad.pop();
		} catch (EmptyStackException e) {
			return null;
		}
	}
	
	public void addFontToLoad(String id, String fontName, int fontSize) {
		fontLoaded = false;
		Object[] o = new Object[] {id, fontName, fontSize};
		fontToLoad.push(o);
	}
	
	public boolean isAllFontLoaded() {
		return fontLoaded;
	}
	
	public void setFontLoaded(boolean fontLoaded) {
		this.fontLoaded = fontLoaded;
	}
	
	public long getTime() {
		return System.currentTimeMillis();
	}
	
	private void updateTick() {
		tick = System.currentTimeMillis() - lastTick;
		lastTick = System.currentTimeMillis();
	}
	
	public void render() {
		if(currentStage!=null && currentStage.isRunning()){
			currentStage.render();
		} 
	}
	
	public void setGameStage( GameStage stage) {
		if(currentStage!= null) {
			while(currentStage.isRunning()) {
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		this.currentStage = stage;
	}
	
	public void run() {
		lastTick = System.currentTimeMillis();
		while(running) {
			update();
		}
	}
	
	public void start() {
		running = true;
		coreThread.start();
	}
	
	public void stop() {
		running = false;
	}
	
	public boolean isRunning() {
		return running;
	}
}
